﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Transactions;


using Global.Class.Library;
using DataTransferObject;
using DataAccessLayer;
using DataAccessLayer.MarketingProgramDTSTableAdapters;


//update MarketingProgramCustomerName
//set MarketingProgramCustomerName.EffectedDate = MarketingProgramMaster.BeginingDate, MarketingProgramCustomerName.Budget = 0
//FROM         MarketingProgramMaster INNER JOIN
//                      MarketingProgramCustomerName ON MarketingProgramMaster.MarketingProgramID = MarketingProgramCustomerName.MarketingProgramID

namespace BusinessLogicLayer
{
    public class MarketingProgramBLL : NotifyPropertyChangeObject
    {
        public GlobalEnum.TaskID TaskID { get { return GlobalEnum.TaskID.MarketingProgram; } }

        private UserInformation userOrganization;

        private MarketingProgramMaster marketingProgramMaster;

        private BindingList<MarketingProgramItemCategory> itemCategoryList;
        private BindingList<MarketingProgramItemCommodity> itemCommodityList;
        private BindingList<MarketingProgramCustomerName> customerNameList;
        private BindingList<MarketingProgramCustomerChannel> customerChannelList;
        private BindingList<MarketingProgramAddressArea> addressAreaList;
        private BindingList<MarketingProgramMechanicScheme> mechanicSchemeList;



        public MarketingProgramBLL()
        {
            try
            {
                if (GlobalVariables.shouldRestoreProcedure) RestoreProcedure();

                userOrganization = new UserInformation();

                marketingProgramMaster = new MarketingProgramMaster();

                this.itemCategoryList = new BindingList<MarketingProgramItemCategory>();
                this.itemCommodityList = new BindingList<MarketingProgramItemCommodity>();
                this.customerNameList = new BindingList<MarketingProgramCustomerName>();
                this.customerChannelList = new BindingList<MarketingProgramCustomerChannel>();
                this.addressAreaList = new BindingList<MarketingProgramAddressArea>();
                this.mechanicSchemeList = new BindingList<MarketingProgramMechanicScheme>();

                GlobalDefaultValue.Apply(this);


                this.MarketingProgramMaster.PropertyChanged += new PropertyChangedEventHandler(MarketingProgramMaster_PropertyChanged);

                this.MechanicSchemeList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);

                this.ItemCategoryList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);
                this.ItemCommodityList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);

                this.AddressAreaList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);
                this.CustomerChannelList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);
                this.CustomerNameList.ListChanged += new ListChangedEventHandler(MarketingProgramDetail_ListChanged);

            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        private void MarketingProgramMaster_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void MarketingProgramDetail_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }




        #region <Adapter>

        private MarketingProgramListingTableAdapter listingTableAdapter;
        protected MarketingProgramListingTableAdapter ListingTableAdapter
        {
            get
            {
                if (listingTableAdapter == null) listingTableAdapter = new MarketingProgramListingTableAdapter();
                return listingTableAdapter;
            }
        }

        private MarketingProgramMasterTableAdapter masterTableAdapter;
        protected MarketingProgramMasterTableAdapter MasterTableAdapter
        {
            get
            {
                if (masterTableAdapter == null) masterTableAdapter = new MarketingProgramMasterTableAdapter();
                return masterTableAdapter;
            }
        }

        MarketingProgramItemCategoryTableAdapter itemCategoryTableAdapter;
        protected MarketingProgramItemCategoryTableAdapter ItemCategoryTableAdapter
        {
            get
            {
                if (itemCategoryTableAdapter == null) itemCategoryTableAdapter = new MarketingProgramItemCategoryTableAdapter();
                return itemCategoryTableAdapter;
            }
        }

        MarketingProgramItemCommodityTableAdapter itemCommodityTableAdapter;
        protected MarketingProgramItemCommodityTableAdapter ItemCommodityTableAdapter
        {
            get
            {
                if (itemCommodityTableAdapter == null) itemCommodityTableAdapter = new MarketingProgramItemCommodityTableAdapter();
                return itemCommodityTableAdapter;
            }
        }

        MarketingProgramAddressAreaTableAdapter addressAreaTableAdapter;
        protected MarketingProgramAddressAreaTableAdapter AddressAreaTableAdapter
        {
            get
            {
                if (addressAreaTableAdapter == null) addressAreaTableAdapter = new MarketingProgramAddressAreaTableAdapter();
                return addressAreaTableAdapter;
            }
        }

        MarketingProgramCustomerChannelTableAdapter customerChannelTableAdapter;
        protected MarketingProgramCustomerChannelTableAdapter CustomerChannelTableAdapter
        {
            get
            {
                if (customerChannelTableAdapter == null) customerChannelTableAdapter = new MarketingProgramCustomerChannelTableAdapter();
                return customerChannelTableAdapter;
            }
        }

        MarketingProgramCustomerNameTableAdapter customerNameTableAdapter;
        protected MarketingProgramCustomerNameTableAdapter CustomerNameTableAdapter
        {
            get
            {
                if (customerNameTableAdapter == null) customerNameTableAdapter = new MarketingProgramCustomerNameTableAdapter();
                return customerNameTableAdapter;
            }
        }

        MarketingProgramMechanicSchemeTableAdapter mechanicSchemeTableAdapter;
        protected MarketingProgramMechanicSchemeTableAdapter MechanicSchemeTableAdapter
        {
            get
            {
                if (mechanicSchemeTableAdapter == null) mechanicSchemeTableAdapter = new MarketingProgramMechanicSchemeTableAdapter();
                return mechanicSchemeTableAdapter;
            }
        }

        #endregion <Adapter>

        #region <Storage>

        public UserInformation UserOrganization
        {
            get { return this.userOrganization; }
            set { this.userOrganization = value; }
        }

        public MarketingProgramDTS.MarketingProgramListingDataTable MarketingProgramMasterList(DateTime lowerFillterDate, DateTime upperFillterDate)
        {
            return this.ListingTableAdapter.GetData(lowerFillterDate, upperFillterDate);
        }

        public MarketingProgramMaster MarketingProgramMaster
        {
            get { return this.marketingProgramMaster; }
        }

        public BindingList<MarketingProgramItemCategory> ItemCategoryList
        {
            get { return this.itemCategoryList; }
        }

        public BindingList<MarketingProgramItemCommodity> ItemCommodityList
        {
            get { return this.itemCommodityList; }
        }

        public BindingList<MarketingProgramAddressArea> AddressAreaList
        {
            get { return this.addressAreaList; }
        }

        public BindingList<MarketingProgramCustomerName> CustomerNameList
        {
            get { return this.customerNameList; }
        }

        public BindingList<MarketingProgramCustomerChannel> CustomerChannelList
        {
            get { return this.customerChannelList; }
        }

        public BindingList<MarketingProgramMechanicScheme> MechanicSchemeList
        {
            get { return this.mechanicSchemeList; }
        }

        #endregion <Storage>

        #region Properties

        #region <Primary Key>

        public int MarketingProgramID   //Primary Key
        {
            get { return this.MarketingProgramMaster.MarketingProgramID; }
            private set
            {
                if (this.MarketingProgramMaster.MarketingProgramID != value)
                {
                    this.StopTracking();

                    this.MarketingProgramMaster.MarketingProgramID = value;

                    this.GetMarketingProgramMaster();
                    this.GetMarketingProgramItemCategory();
                    this.GetMarketingProgramItemCommodity();
                    this.GetMarketingProgramCustomerName();
                    this.GetMarketingProgramCustomerChannel();
                    this.GetMarketingProgramAddressArea();
                    this.GetMarketingProgramMechanicScheme();

                    this.StartTracking();
                    this.Reset();
                }

            }
        }

        #endregion <Primary Key>

        private void GetMarketingProgramMaster()
        {
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramMasterDataTable masterDataTable = this.MasterTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (masterDataTable.Count > 0)
                {
                    this.MarketingProgramMaster.StopTracking();

                    this.MarketingProgramMaster.Reference = masterDataTable[0].Reference;
                    this.MarketingProgramMaster.ReferenceCode = masterDataTable[0].ReferenceCode;
                    this.MarketingProgramMaster.MarketingProgramName = masterDataTable[0].MarketingProgramName;
                    this.MarketingProgramMaster.MarketingProgramSubName = masterDataTable[0].MarketingProgramSubName;
                    this.MarketingProgramMaster.SalesmenID = masterDataTable[0].SalesmenID;
                    this.MarketingProgramMaster.MarketingProgramGroupID = masterDataTable[0].MarketingProgramGroupID;
                    this.MarketingProgramMaster.MarketingProgramTypeID = masterDataTable[0].MarketingProgramTypeID;
                    this.MarketingProgramMaster.CustomerChannelID = masterDataTable[0].CustomerChannelID;
                    this.MarketingProgramMaster.TimeBaseID = masterDataTable[0].TimeBaseID;
                    this.MarketingProgramMaster.BeginingDate = masterDataTable[0].BeginingDate;
                    this.MarketingProgramMaster.EndingDate = masterDataTable[0].EndingDate;
                    this.MarketingProgramMaster.SalesTarget = masterDataTable[0].SalesTarget;
                    this.MarketingProgramMaster.MarketingBudget = masterDataTable[0].MarketingBudget;
                    this.MarketingProgramMaster.Remarks = masterDataTable[0].Remarks;
                    this.MarketingProgramMaster.InActive = masterDataTable[0].InActive;

                    this.MarketingProgramMaster.StartTracking();

                    this.MarketingProgramMaster.Reset();

                    this.UserOrganization.UserID = masterDataTable[0].UserID;
                    this.UserOrganization.UserOrganizationID = masterDataTable[0].UserOrganizationID;
                }
                else throw new System.ArgumentException("Insufficient get data");
            }
            else
            {
                GlobalDefaultValue.Apply(this.MarketingProgramMaster);
                this.MarketingProgramMaster.BeginingDate = DateTime.Today;
                this.MarketingProgramMaster.EndingDate = DateTime.Today.AddDays(365);
                this.MarketingProgramMaster.Reset();
            }
        }


        private void GetMarketingProgramItemCategory()
        {
            this.itemCategoryList.RaiseListChangedEvents = false;
            this.itemCategoryList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramItemCategoryDataTable itemCategoryDataTable = this.ItemCategoryTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (itemCategoryDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramItemCategoryRow itemCategoryRow in itemCategoryDataTable.Rows)
                    {
                        this.itemCategoryList.Add(new MarketingProgramItemCategory(itemCategoryRow.ItemCategoryID, itemCategoryRow.SharingSalesTarget, itemCategoryRow.Remarks));
                    }
                }
            }
            this.itemCategoryList.RaiseListChangedEvents = true;
            this.itemCategoryList.ResetBindings();
        }


        private void GetMarketingProgramItemCommodity()
        {
            this.itemCommodityList.RaiseListChangedEvents = false;
            this.itemCommodityList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramItemCommodityDataTable itemCommodityDataTable = this.ItemCommodityTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (itemCommodityDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramItemCommodityRow itemCommodityRow in itemCommodityDataTable.Rows)
                    {
                        this.itemCommodityList.Add(new MarketingProgramItemCommodity(itemCommodityRow.CommodityID, itemCommodityRow.SharingSalesTarget, itemCommodityRow.Remarks));
                    }
                }
            }
            this.itemCommodityList.RaiseListChangedEvents = true;
            this.itemCommodityList.ResetBindings();
        }


        private void GetMarketingProgramAddressArea()
        {
            this.addressAreaList.RaiseListChangedEvents = false;
            this.addressAreaList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramAddressAreaDataTable addressAreaDataTable = this.AddressAreaTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (addressAreaDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramAddressAreaRow addressAreaRow in addressAreaDataTable.Rows)
                    {
                        this.addressAreaList.Add(new MarketingProgramAddressArea(addressAreaRow.AddressAreaID, addressAreaRow.Remarks));
                    }
                }
            }
            this.addressAreaList.RaiseListChangedEvents = true;
            this.addressAreaList.ResetBindings();
        }


        private void GetMarketingProgramCustomerChannel()
        {
            this.customerChannelList.RaiseListChangedEvents = false;
            this.customerChannelList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramCustomerChannelDataTable customerChannelDataTable = this.CustomerChannelTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (customerChannelDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramCustomerChannelRow customerChannelRow in customerChannelDataTable.Rows)
                    {
                        this.customerChannelList.Add(new MarketingProgramCustomerChannel(customerChannelRow.CustomerChannelID, customerChannelRow.Remarks));
                    }
                }
            }
            this.customerChannelList.RaiseListChangedEvents = true;
            this.customerChannelList.ResetBindings();
        }


        private void GetMarketingProgramCustomerName()
        {
            this.customerNameList.RaiseListChangedEvents = false;
            this.customerNameList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramCustomerNameDataTable customerNameDataTable = this.CustomerNameTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (customerNameDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramCustomerNameRow customerNameRow in customerNameDataTable.Rows)
                    {
                        this.customerNameList.Add(new MarketingProgramCustomerName(customerNameRow.CustomerID, customerNameRow.EffectedDate, customerNameRow.SalesTarget, customerNameRow.Remarks));
                    }
                }
            }
            this.customerNameList.RaiseListChangedEvents = true;
            this.customerNameList.ResetBindings();
        }


        private void GetMarketingProgramMechanicScheme()
        {
            this.mechanicSchemeList.RaiseListChangedEvents = false;
            this.mechanicSchemeList.Clear();
            if (this.MarketingProgramID > 0)
            {
                MarketingProgramDTS.MarketingProgramMechanicSchemeDataTable mechanicSchemeDataTable = this.MechanicSchemeTableAdapter.GetDataByMarketingProgramID(this.MarketingProgramID);

                if (mechanicSchemeDataTable.Count > 0)
                {
                    foreach (MarketingProgramDTS.MarketingProgramMechanicSchemeRow mechanicSchemeRow in mechanicSchemeDataTable.Rows)
                    {
                        this.mechanicSchemeList.Add(new MarketingProgramMechanicScheme(mechanicSchemeRow.MechanicSchemeID, mechanicSchemeRow.Description, mechanicSchemeRow.Remarks));
                    }
                }
            }
            this.mechanicSchemeList.RaiseListChangedEvents = true;
            this.mechanicSchemeList.ResetBindings();
        }


        #endregion Properties





        #region Object Permission

        public override bool IsValid
        {
            get
            {
                List<MarketingProgramAddressArea> inValidMarketingProgramAddressArea = this.AddressAreaList.Where(marketingProgramAddressArea => !marketingProgramAddressArea.IsValid).ToList();
                List<MarketingProgramCustomerChannel> inValidMarketingProgramCustomerChannel = this.CustomerChannelList.Where(marketingProgramCustomerChannel => !marketingProgramCustomerChannel.IsValid).ToList();
                List<MarketingProgramCustomerName> inValidMarketingProgramCustomerName = this.CustomerNameList.Where(marketingProgramCustomerName => !marketingProgramCustomerName.IsValid).ToList();
                List<MarketingProgramItemCategory> inValidMarketingProgramItemCategory = this.ItemCategoryList.Where(marketingProgramItemCategory => !marketingProgramItemCategory.IsValid).ToList();
                List<MarketingProgramItemCommodity> inValidMarketingProgramItemCommodity = this.ItemCommodityList.Where(marketingProgramItemCommodity => !marketingProgramItemCommodity.IsValid).ToList();
                List<MarketingProgramMechanicScheme> inValidMarketingProgramMechanicScheme = this.MechanicSchemeList.Where(marketingProgramMechanicScheme => !marketingProgramMechanicScheme.IsValid).ToList();

                return this.MarketingProgramMaster.IsValid && inValidMarketingProgramAddressArea.Count == 0 && inValidMarketingProgramCustomerChannel.Count == 0 && inValidMarketingProgramCustomerName.Count == 0 && inValidMarketingProgramItemCategory.Count == 0 && inValidMarketingProgramItemCommodity.Count == 0 && inValidMarketingProgramMechanicScheme.Count == 0;
            }
        }

        public bool ReadOnly
        {
            get
            {
                try
                {
                    return GlobalUserPermission.GetUserReadOnly(GlobalVariables.GlobalUserInformation.UserID, this.TaskID);
                }
                catch
                {
                    return true;
                }
            }
        }

        public bool Editable
        {
            get
            {
                try
                {
                    if (this.marketingProgramMaster.BeginingDate <= GlobalUserPermission.GlobalLockedDate()) return false;

                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, this.TaskID, this.UserOrganization.UserOrganizationID)) return false;

                    if (!GlobalUserPermission.GetEditable("SPMarketingProgramApproved", this.MarketingProgramID)) return false;

                    return GlobalUserPermission.GetEditable("SPMarketingProgramEditable", this.MarketingProgramID);
                }
                catch (Exception exception)
                {
                    throw exception;
                    //return false;
                }
            }
        }

        public bool Verifiable
        {
            get
            {
                try
                {
                    if (this.marketingProgramMaster.BeginingDate <= GlobalUserPermission.GlobalLockedDate()) return false;

                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.MarketingProgramVerifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("SPMarketingProgramEditable", this.MarketingProgramID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Unverifiable
        {
            get
            {
                try
                {
                    if (this.marketingProgramMaster.BeginingDate <= GlobalUserPermission.GlobalLockedDate()) return false;

                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.MarketingProgramUnverifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("SPMarketingProgramEditable", this.MarketingProgramID);
                }
                catch
                {
                    return false;
                }
            }
        }


        #endregion Object Permission






        public void Fill(int marketingProgramID)
        {
            if (this.MarketingProgramID == marketingProgramID) this.MarketingProgramID = -1; //Enforce to reload
            this.MarketingProgramID = marketingProgramID;
        }

        public void New()
        {
            if (this.MarketingProgramID == 0) this.MarketingProgramID = -1;
            this.MarketingProgramID = 0;
        }

        public void Edit()
        {

        }

        #region Save & Delete Method


        public bool Save()
        {
            int marketingProgramID = 0;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient save", "Save validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    //if (!this.Editable) throw new System.ArgumentException("Insufficient save", "Uneditable");

                    if (!this.SaveMaster(ref marketingProgramID)) throw new System.ArgumentException("Insufficient save", "Save master");

                    if (!this.SaveDetail(marketingProgramID)) throw new System.ArgumentException("Insufficient save", "Save detail");

                    if (this.SaveConflict()) throw new System.ArgumentException("Insufficient save", "Save conflict");

                    transactionScope.Complete();                    //northwindDataSet.AcceptChanges();
                }

                this.Fill(marketingProgramID);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        public bool Delete()
        {
            if (this.marketingProgramMaster.MarketingProgramID <= 0) return false;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient delete", "Delete validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (!this.Editable) throw new System.ArgumentException("Insufficient delete", "Uneditable");

                    if (!this.SaveUndo(this.marketingProgramMaster.MarketingProgramID)) throw new System.ArgumentException("Insufficient delete", "Delete detail");

                    if (this.MasterTableAdapter.Delete(this.marketingProgramMaster.MarketingProgramID) != 1) throw new System.ArgumentException("Insufficient delete", "Delete master");

                    if (this.SaveConflict()) throw new System.ArgumentException("Insufficient delete", "Delete conflict");

                    transactionScope.Complete();                    //northwindDataSet.AcceptChanges();
                }
                this.Fill(0);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        private bool SaveValidate()
        {
            ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

            this.UserOrganization = GlobalUserPermission.GetUserInformation(this.MarketingProgramMaster.SalesmenID, this.MarketingProgramMaster.BeginingDate);

            if (this.UserOrganization.UserID <= 0 || this.UserOrganization.UserOrganizationID <= 0) exceptionTable.AddException(new string[] { GlobalVariables.stringFieldRequired, "User information" });


            if (exceptionTable.Table.Rows.Count <= 0 && this.IsValid) return true; else throw new CustomException("Save validate", exceptionTable.Table);
        }


        private bool SaveMaster(ref int marketingProgramID)
        {
            MarketingProgramDTS.MarketingProgramMasterDataTable masterDataTable;
            MarketingProgramDTS.MarketingProgramMasterRow masterRow;

            if (this.marketingProgramMaster.MarketingProgramID <= 0) //Add
            {
                masterDataTable = new MarketingProgramDTS.MarketingProgramMasterDataTable();
                masterRow = masterDataTable.NewMarketingProgramMasterRow();
            }
            else //Edit
            {
                if (!this.SaveUndo(marketingProgramMaster.MarketingProgramID)) throw new System.ArgumentException("Insufficient save", "Save undo");
                masterDataTable = this.MasterTableAdapter.GetDataByMarketingProgramID(marketingProgramMaster.MarketingProgramID);
                if (masterDataTable.Count > 0) masterRow = masterDataTable[0]; else throw new System.ArgumentException("Insufficient save", "Get for edit");
            }

            masterRow.ReferenceCode = this.marketingProgramMaster.ReferenceCode;
            masterRow.Reference = this.marketingProgramMaster.Reference;
            masterRow.MarketingProgramName = this.marketingProgramMaster.MarketingProgramName;
            masterRow.MarketingProgramSubName = this.marketingProgramMaster.MarketingProgramSubName;
            masterRow.SalesmenID = this.marketingProgramMaster.SalesmenID;
            masterRow.MarketingProgramGroupID = this.marketingProgramMaster.MarketingProgramGroupID;
            masterRow.MarketingProgramTypeID = this.marketingProgramMaster.MarketingProgramTypeID;
            masterRow.CustomerChannelID = this.marketingProgramMaster.CustomerChannelID;
            masterRow.TimeBaseID = this.marketingProgramMaster.TimeBaseID;
            masterRow.BeginingDate = this.marketingProgramMaster.BeginingDate;
            masterRow.EndingDate = this.marketingProgramMaster.EndingDate;
            masterRow.SalesTarget = this.marketingProgramMaster.SalesTarget;
            masterRow.MarketingBudget = this.marketingProgramMaster.MarketingBudget;
            masterRow.Remarks = this.marketingProgramMaster.Remarks;
            masterRow.InActive = this.marketingProgramMaster.InActive;

            masterRow.UserID = this.UserOrganization.UserID;
            masterRow.UserOrganizationID = this.UserOrganization.UserOrganizationID;

            if (this.marketingProgramMaster.MarketingProgramID <= 0) masterDataTable.AddMarketingProgramMasterRow(masterRow);

            int rowsAffected = this.MasterTableAdapter.Update(masterRow);

            marketingProgramID = masterRow.MarketingProgramID;

            return rowsAffected == 1;
        }


        private bool SaveDetail(int marketingProgramID)
        {
            int serialID = 0; int rowsAffected = 0;


            #region <Item Category>

            serialID = 0;

            MarketingProgramDTS.MarketingProgramItemCategoryDataTable itemCategoryDataTable = new MarketingProgramDTS.MarketingProgramItemCategoryDataTable();

            foreach (MarketingProgramItemCategory itemCategory in this.itemCategoryList)
            {
                MarketingProgramDTS.MarketingProgramItemCategoryRow itemCategoryRow = itemCategoryDataTable.NewMarketingProgramItemCategoryRow();

                itemCategoryRow.MarketingProgramID = marketingProgramID;
                itemCategoryRow.SerialID = ++serialID;

                itemCategoryRow.ItemCategoryID = itemCategory.ItemCategoryID;
                itemCategoryRow.SharingSalesTarget = itemCategory.SharingSalesTarget;
                itemCategoryRow.Remarks = itemCategory.Remarks;
                itemCategoryDataTable.AddMarketingProgramItemCategoryRow(itemCategoryRow);
            }

            rowsAffected = this.ItemCategoryTableAdapter.Update(itemCategoryDataTable);
            if (rowsAffected != this.itemCategoryList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Item Category");


            #endregion <Item Category>


            #region <Item Commodity>

            serialID = 0;

            MarketingProgramDTS.MarketingProgramItemCommodityDataTable itemCommodityDataTable = new MarketingProgramDTS.MarketingProgramItemCommodityDataTable();

            foreach (MarketingProgramItemCommodity itemCommodity in this.itemCommodityList)
            {
                MarketingProgramDTS.MarketingProgramItemCommodityRow itemCommodityRow = itemCommodityDataTable.NewMarketingProgramItemCommodityRow();

                itemCommodityRow.MarketingProgramID = marketingProgramID;
                itemCommodityRow.SerialID = ++serialID;

                itemCommodityRow.CommodityID = itemCommodity.CommodityID;
                itemCommodityRow.SharingSalesTarget = itemCommodity.SharingSalesTarget;
                itemCommodityRow.Remarks = itemCommodity.Remarks;

                itemCommodityDataTable.AddMarketingProgramItemCommodityRow(itemCommodityRow);
            }

            rowsAffected = this.ItemCommodityTableAdapter.Update(itemCommodityDataTable);
            if (rowsAffected != this.itemCommodityList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Item Commodity");


            #endregion <Item Commodity>


            #region <Address Area>

            serialID = 0;
            MarketingProgramDTS.MarketingProgramAddressAreaDataTable addressAreaDataTable = new MarketingProgramDTS.MarketingProgramAddressAreaDataTable();

            foreach (MarketingProgramAddressArea addressArea in this.addressAreaList)
            {
                MarketingProgramDTS.MarketingProgramAddressAreaRow addressAreaRow = addressAreaDataTable.NewMarketingProgramAddressAreaRow();

                addressAreaRow.MarketingProgramID = marketingProgramID;
                addressAreaRow.SerialID = ++serialID;

                addressAreaRow.AddressAreaID = addressArea.AddressAreaID;
                addressAreaRow.Remarks = addressArea.Remarks;

                addressAreaDataTable.AddMarketingProgramAddressAreaRow(addressAreaRow);
            }

            rowsAffected = this.AddressAreaTableAdapter.Update(addressAreaDataTable);
            if (rowsAffected != this.addressAreaList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Address Area");


            #endregion <Address Area>


            #region <Customer Channel>

            serialID = 0;

            MarketingProgramDTS.MarketingProgramCustomerChannelDataTable customerChannelDataTable = new MarketingProgramDTS.MarketingProgramCustomerChannelDataTable();

            foreach (MarketingProgramCustomerChannel customerChannel in this.customerChannelList)
            {
                MarketingProgramDTS.MarketingProgramCustomerChannelRow customerChannelRow = customerChannelDataTable.NewMarketingProgramCustomerChannelRow();

                customerChannelRow.MarketingProgramID = marketingProgramID;
                customerChannelRow.SerialID = ++serialID;

                customerChannelRow.CustomerChannelID = customerChannel.CustomerChannelID;
                customerChannelRow.Remarks = customerChannel.Remarks;

                customerChannelDataTable.AddMarketingProgramCustomerChannelRow(customerChannelRow);
            }

            rowsAffected = this.CustomerChannelTableAdapter.Update(customerChannelDataTable);
            if (rowsAffected != this.customerChannelList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Customer Channel");


            #endregion <Customer Channel>


            #region <Customer Name>

            serialID = 0;

            MarketingProgramDTS.MarketingProgramCustomerNameDataTable customerNameDataTable = new MarketingProgramDTS.MarketingProgramCustomerNameDataTable();

            foreach (MarketingProgramCustomerName customerName in this.customerNameList)
            {
                MarketingProgramDTS.MarketingProgramCustomerNameRow customerNameRow = customerNameDataTable.NewMarketingProgramCustomerNameRow();

                customerNameRow.MarketingProgramID = marketingProgramID;
                customerNameRow.SerialID = ++serialID;

                customerNameRow.CustomerID = customerName.CustomerID;
                customerNameRow.EffectedDate = customerName.EffectedDate;
                customerNameRow.SalesTarget = customerName.SalesTarget;
                customerNameRow.Remarks = customerName.Remarks;

                customerNameDataTable.AddMarketingProgramCustomerNameRow(customerNameRow);
            }

            rowsAffected = this.CustomerNameTableAdapter.Update(customerNameDataTable);
            if (rowsAffected != this.customerNameList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Customer Name");


            #endregion <Customer Name>


            #region <Mechanic Scheme>

            serialID = 0;

            MarketingProgramDTS.MarketingProgramMechanicSchemeDataTable mechanicSchemeDataTable = new MarketingProgramDTS.MarketingProgramMechanicSchemeDataTable();

            foreach (MarketingProgramMechanicScheme mechanicScheme in this.mechanicSchemeList)
            {
                MarketingProgramDTS.MarketingProgramMechanicSchemeRow mechanicSchemeRow = mechanicSchemeDataTable.NewMarketingProgramMechanicSchemeRow();

                mechanicSchemeRow.MarketingProgramID = marketingProgramID;
                mechanicSchemeRow.SerialID = ++serialID;

                mechanicSchemeRow.MechanicSchemeID = mechanicScheme.MechanicSchemeID;
                mechanicSchemeRow.Description = mechanicScheme.Description;
                mechanicSchemeRow.Remarks = mechanicScheme.Remarks;

                mechanicSchemeDataTable.AddMarketingProgramMechanicSchemeRow(mechanicSchemeRow);
            }

            rowsAffected = this.MechanicSchemeTableAdapter.Update(mechanicSchemeDataTable);
            if (rowsAffected != this.mechanicSchemeList.Count) throw new System.ArgumentException("Insufficient save", "Save detail: Mechanic Scheme");


            #endregion <Mechanic Scheme>


            return true;
        }


        private bool SaveUndo(int marketingProgramID)
        {
            this.AddressAreaTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);
            this.CustomerChannelTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);
            this.CustomerNameTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);

            this.ItemCategoryTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);
            this.ItemCommodityTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);

            this.MechanicSchemeTableAdapter.DeleteWholeMarketingProgram(marketingProgramID);

            return true;
        }


        private bool SaveConflict()
        {
            return false;
        }



        #endregion



        #region Import Excel

        public bool ImportMarketingProgram(string fileName)
        {
            try
            {
                DateTime dateTimeValue; float floatValue;
                ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

                TimeSpan timeout = TimeSpan.FromMinutes(30);
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, timeout))
                {
                    if (this.ReadOnly) throw new System.ArgumentException("Import", "Permission conflict");

                    DataTable excelDataTable = OleDbDatabase.OpenExcelSheet(OleDbDatabase.MappingTaskID.MarketingProgram, fileName);
                    if (excelDataTable != null && excelDataTable.Rows.Count > 0)
                    {
                        string[] splitStringArray;
                        foreach (DataRow excelDataRow in excelDataTable.Rows)
                        {
                            exceptionTable.ClearDirty();

                            MarketingProgramBLL importMarketingProgramBLL = new MarketingProgramBLL();
                            importMarketingProgramBLL.New();

                            importMarketingProgramBLL.marketingProgramMaster.ReferenceCode = excelDataRow["ReferenceCode"].ToString();
                            importMarketingProgramBLL.marketingProgramMaster.Reference = excelDataRow["Reference"].ToString();
                            importMarketingProgramBLL.marketingProgramMaster.MarketingProgramName = excelDataRow["MarketingProgramName"].ToString();
                            importMarketingProgramBLL.marketingProgramMaster.MarketingProgramSubName = excelDataRow["MarketingProgramSubName"].ToString();

                            ERmgrUIP.ListStaffNameRow listStaffNameRow = CommonDatabaseMethod.GetStaffName(0, excelDataRow["SalesmenID"].ToString().Trim());
                            if (listStaffNameRow != null)
                                importMarketingProgramBLL.marketingProgramMaster.SalesmenID = listStaffNameRow.StaffID;
                            else
                            {//Handle exception when ItemType can not be found
                                exceptionTable.AddException(new string[] { "Staffs", excelDataRow["SalesmenID"].ToString() });
                            }

                            if (DateTime.TryParse(excelDataRow["BeginingDate"].ToString(), out dateTimeValue)) importMarketingProgramBLL.marketingProgramMaster.BeginingDate = dateTimeValue; else exceptionTable.AddException(new string[] { "Invalid Date Value", excelDataRow["BeginingDate"].ToString() });
                            if (DateTime.TryParse(excelDataRow["EndingDate"].ToString(), out dateTimeValue)) importMarketingProgramBLL.marketingProgramMaster.EndingDate = dateTimeValue; else exceptionTable.AddException(new string[] { "Invalid Date Value", excelDataRow["EndingDate"].ToString() });

                            if (float.TryParse(excelDataRow["SalesTarget"].ToString(), out floatValue)) importMarketingProgramBLL.marketingProgramMaster.SalesTarget = floatValue; else exceptionTable.AddException(new string[] { "Invalid Number Value", excelDataRow["SalesTarget"].ToString() });
                            if (float.TryParse(excelDataRow["MarketingBudget"].ToString(), out floatValue)) importMarketingProgramBLL.marketingProgramMaster.MarketingBudget = floatValue; else exceptionTable.AddException(new string[] { "Invalid Number Value", excelDataRow["MarketingBudget"].ToString() });

                            importMarketingProgramBLL.marketingProgramMaster.Remarks = excelDataRow["Remarks"].ToString();


                            //CustomerChannelList
                            if (excelDataRow["PrimaryCustomerChannelID"].ToString() != "")
                            {
                                ERmgrUIP.SPGetCustomerChannelRow customerChannelRow = CommonDatabaseMethod.GetCustomerChannel(0, excelDataRow["PrimaryCustomerChannelID"].ToString().Trim(), true);
                                if (customerChannelRow != null)
                                    importMarketingProgramBLL.marketingProgramMaster.CustomerChannelID = customerChannelRow.CustomerChannelID;
                                else
                                {//Handle exception when CustomerChannel can not be found
                                    exceptionTable.AddException(new string[] { "Customer Channel", excelDataRow["PrimaryCustomerChannelID"].ToString() });
                                }
                            }


                            //MarketingProgramGroupList
                            if (excelDataRow["MarketingProgramGroupID"].ToString() != "")
                            {
                                ERmgrUIP.SPGetMarketingProgramGroupRow marketingProgramGroupRow = CommonDatabaseMethod.GetMarketingProgramGroup(0, excelDataRow["MarketingProgramGroupID"].ToString().Trim());
                                if (marketingProgramGroupRow != null)
                                    importMarketingProgramBLL.marketingProgramMaster.MarketingProgramGroupID = marketingProgramGroupRow.MarketingProgramGroupID;
                                else
                                {//Handle exception when MarketingProgramGroup can not be found
                                    exceptionTable.AddException(new string[] { "Marketing Program Group", excelDataRow["MarketingProgramGroupID"].ToString() });
                                }
                            }

                            //MarketingProgramTypeList
                            if (excelDataRow["MarketingProgramTypeID"].ToString() != "")
                            {
                                ERmgrUIP.SPGetMarketingProgramTypeRow marketingProgramTypeRow = CommonDatabaseMethod.GetMarketingProgramType(0, excelDataRow["MarketingProgramTypeID"].ToString().Trim());
                                if (marketingProgramTypeRow != null)
                                    importMarketingProgramBLL.marketingProgramMaster.MarketingProgramTypeID = marketingProgramTypeRow.MarketingProgramTypeID;
                                else
                                {//Handle exception when MarketingProgramType can not be found
                                    exceptionTable.AddException(new string[] { "Marketing Program Type", excelDataRow["MarketingProgramTypeID"].ToString() });
                                }
                            }


                            //TimeBaseList
                            if (excelDataRow["TimeBaseID"].ToString() != "")
                            {
                                ERmgrUIP.SPGetTimeBaseRow timeBaseRow = CommonDatabaseMethod.GetTimeBase(0, excelDataRow["TimeBaseID"].ToString().Trim());
                                if (timeBaseRow != null)
                                    importMarketingProgramBLL.marketingProgramMaster.TimeBaseID = timeBaseRow.TimeBaseID;
                                else
                                {//Handle exception when TimeBase can not be found
                                    exceptionTable.AddException(new string[] { "Time Base", excelDataRow["TimeBaseID"].ToString() });
                                }
                            }



                            #region Detail Collection

                            //MechanicSchemeList
                            if (excelDataRow["MechanicSchemeID"].ToString() != "")
                            {
                                importMarketingProgramBLL.MechanicSchemeList.Add(new MarketingProgramMechanicScheme(1, excelDataRow["MechanicSchemeID"].ToString(), ""));
                            }

                            //ItemCategoryList
                            if (excelDataRow["ItemCategoryID"].ToString() != "")
                            {
                                splitStringArray = excelDataRow["ItemCategoryID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetItemCategoryRow itemCategoryRow = CommonDatabaseMethod.GetItemCategory(0, splitString.Trim());
                                    if (itemCategoryRow != null)
                                        importMarketingProgramBLL.ItemCategoryList.Add(new MarketingProgramItemCategory(itemCategoryRow.ItemCategoryID, 0, ""));
                                    else
                                    {//Handle exception when ItemCategory can not be found
                                        exceptionTable.AddException(new string[] { "Item Category", splitString.Trim() });
                                    }
                                }
                            }


                            //ItemCommodityList
                            if (excelDataRow["CommodityID"].ToString() != "")
                            {
                                splitStringArray = excelDataRow["CommodityID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetItemCommodityRow itemCommodityRow = CommonDatabaseMethod.GetItemCommodity(0, splitString.Trim());
                                    if (itemCommodityRow != null)
                                        importMarketingProgramBLL.ItemCommodityList.Add(new MarketingProgramItemCommodity(itemCommodityRow.CommodityID, 0, ""));
                                    else
                                    {//Handle exception when ItemCommodity can not be found
                                        exceptionTable.AddException(new string[] { "Item Commodity", splitString.Trim() });
                                    }
                                }
                            }


                            //AddressAreaList
                            if (excelDataRow["AddressAreaID"].ToString() != "")
                            {
                                splitStringArray = excelDataRow["AddressAreaID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetAddressAreaRow addressAreaRow = CommonDatabaseMethod.GetAddressArea(0, splitString.Trim());
                                    if (addressAreaRow != null)
                                        importMarketingProgramBLL.AddressAreaList.Add(new MarketingProgramAddressArea(addressAreaRow.AddressAreaID, ""));
                                    else
                                    {//Handle exception when AddressArea can not be found
                                        exceptionTable.AddException(new string[] { "Territory", splitString.Trim() });
                                    }
                                }
                            }


                            //CustomerChannelList
                            if (excelDataRow["CustomerChannelID"].ToString() != "")
                            {
                                splitStringArray = excelDataRow["CustomerChannelID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetCustomerChannelRow customerChannelRow = CommonDatabaseMethod.GetCustomerChannel(0, splitString.Trim(), false);
                                    if (customerChannelRow != null)
                                        importMarketingProgramBLL.CustomerChannelList.Add(new MarketingProgramCustomerChannel(customerChannelRow.CustomerChannelID, ""));
                                    else
                                    {//Handle exception when CustomerChannel can not be found
                                        exceptionTable.AddException(new string[] { "Customer Channel", splitString.Trim() });
                                    }
                                }
                            }


                            //CustomerNameList
                            if (excelDataRow["CustomerID"].ToString() != "")
                            {
                                splitStringArray = excelDataRow["CustomerID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetCustomerNameRow customerNameRow = CommonDatabaseMethod.GetCustomerName(0, splitString.Trim());
                                    if (customerNameRow != null)
                                        importMarketingProgramBLL.CustomerNameList.Add(new MarketingProgramCustomerName(customerNameRow.CustomerID,importMarketingProgramBLL.marketingProgramMaster.BeginingDate, 0, ""));
                                    else
                                    {//Handle exception when CustomerName can not be found
                                        exceptionTable.AddException(new string[] { "Customer", splitString.Trim() });
                                    }
                                }
                            }

                            #endregion Detail Collection

                            if (!exceptionTable.IsDirty)
                                if (importMarketingProgramBLL.IsDirty && !importMarketingProgramBLL.Save())
                                    exceptionTable.AddException(new string[] { "Insufficient save", importMarketingProgramBLL.MarketingProgramMaster.Reference + " [" + importMarketingProgramBLL.MarketingProgramMaster.ReferenceCode + "]" });
                        }

                    }

                    if (exceptionTable.Table.Rows.Count <= 0)
                        transactionScope.Complete();
                    else
                        throw new CustomException("Invalid data value or data entry not found", exceptionTable.Table);
                }


                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }

        }


        public bool ImportMarketingCustomer(string fileName)
        {
            try
            {
                if (this.ReadOnly) throw new System.ArgumentException("Import", "Permission conflict"); // || !this.IsDirty

                MarketingProgramBLL importMarketingProgramBLL = new MarketingProgramBLL();
                importMarketingProgramBLL.New();

                ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

                DataTable excelDataTable = OleDbDatabase.OpenExcelSheet(OleDbDatabase.MappingTaskID.MarketingCustomer, fileName);
                if (excelDataTable != null && excelDataTable.Rows.Count > 0)
                {
                    importMarketingProgramBLL.CustomerNameList.RaiseListChangedEvents = false;
                    string[] splitStringArray; DateTime effectedDate; double salesTarget;
                    foreach (DataRow excelDataRow in excelDataTable.Rows)
                    {
                        if (excelDataRow["CustomerID"].ToString() != "")
                        {
                            if (DateTime.TryParse(excelDataRow["EffectedDate"].ToString(), out effectedDate) && double.TryParse(excelDataRow["SalesTarget"].ToString(), out salesTarget))
                            {
                                splitStringArray = excelDataRow["CustomerID"].ToString().Split(';');
                                foreach (string splitString in splitStringArray)
                                {
                                    ERmgrUIP.SPGetCustomerNameRow customerNameRow = CommonDatabaseMethod.GetCustomerName(0, splitString.Trim());
                                    if (customerNameRow != null)
                                        importMarketingProgramBLL.CustomerNameList.Add(new MarketingProgramCustomerName(customerNameRow.CustomerID, effectedDate, salesTarget, excelDataRow["Remarks"].ToString()));
                                    else
                                    {//Handle exception when CustomerName can not be found
                                        exceptionTable.AddException(new string[] { "Customer", splitString.Trim() });
                                    }
                                }
                            }
                            else
                                exceptionTable.AddException(new string[] { "Invalid effectedDate or salesTarget", excelDataRow["EffectedDate"].ToString() + " [" + excelDataRow["SalesTarget"].ToString() + "]" });
                        }

                    }
                    importMarketingProgramBLL.CustomerNameList.RaiseListChangedEvents = true;
                    importMarketingProgramBLL.CustomerNameList.ResetBindings();
                }

                if (exceptionTable.Table.Rows.Count <= 0)
                {
                    this.CustomerNameList.RaiseListChangedEvents = false;
                    foreach (MarketingProgramCustomerName customerName in importMarketingProgramBLL.customerNameList)
                    {
                        this.CustomerNameList.Add(new MarketingProgramCustomerName(customerName.CustomerID, customerName.EffectedDate, customerName.SalesTarget, customerName.Remarks));
                    }
                    this.CustomerNameList.RaiseListChangedEvents = true;
                    this.CustomerNameList.ResetBindings();
                }
                else
                    throw new CustomException("Invalid data value or data entry not found", exceptionTable.Table);

                return true;
            }
            catch (System.Exception exception)
            {
                this.CustomerNameList.RaiseListChangedEvents = true;
                throw exception;
            }

        }


        #endregion Import Excel



        private void RestoreProcedure()
        {

            string queryString;
            string[] queryArray;


            queryString = "     @LowerFillterDate DateTime, @UpperFillterDate DateTime " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      LEFT(CONVERT(char(10), MarketingProgramMaster.BeginingDate, 111), 7) AS BeginingMonth, MarketingProgramMaster.MarketingProgramID, MarketingProgramMaster.Reference, MarketingProgramMaster.ReferenceCode, " + "\r\n";
            queryString = queryString + "                   MarketingProgramMaster.MarketingProgramName, MarketingProgramMaster.MarketingProgramSubName, ListMarketingProgramType.Description AS MarketingProgramTypeName, ListMarketingProgramGroup.Description AS MarketingProgramGroupName, ListCustomerChannel.Description AS CustomerChannelName, ListTimeBase.Description AS TimeBaseName, " + "\r\n";
            queryString = queryString + "                   MarketingProgramMaster.BeginingDate, MarketingProgramMaster.EndingDate, MarketingProgramMaster.SalesTarget, MarketingProgramMaster.MarketingBudget " + "\r\n";
            queryString = queryString + "       FROM        MarketingProgramMaster INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListMarketingProgramGroup ON MarketingProgramMaster.MarketingProgramGroupID = ListMarketingProgramGroup.MarketingProgramGroupID INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListMarketingProgramType ON MarketingProgramMaster.MarketingProgramTypeID = ListMarketingProgramType.MarketingProgramTypeID INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListCustomerChannel ON MarketingProgramMaster.CustomerChannelID = ListCustomerChannel.CustomerChannelID INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListTimeBase ON MarketingProgramMaster.TimeBaseID = ListTimeBase.TimeBaseID " + "\r\n";
            queryString = queryString + "       WHERE       MarketingProgramMaster.BeginingDate >= @LowerFillterDate AND MarketingProgramMaster.BeginingDate <= @UpperFillterDate " + "\r\n";

            SQLDatabase.CreateStoredProcedure("MarketingProgramListing", queryString);





            /// <summary>
            /// Check for editable
            /// </summary>
            queryArray = new string[1];
            queryArray[0] = " SELECT TOP 1 MarketingProgramID FROM MarketingProgramMaster WHERE MarketingProgramID = @FindIdentityID AND Approved = 1 ";

            SQLDatabase.CreateProcedureToCheckExisting("SPMarketingProgramApproved", queryArray);



            /// <summary>
            /// Check for editable
            /// </summary>
            queryArray = new string[1];
            queryArray[0] = " SELECT TOP 1 MarketingProgramID FROM MarketingIncentiveMaster WHERE MarketingProgramID = @FindIdentityID ";

            SQLDatabase.CreateProcedureToCheckExisting("SPMarketingProgramEditable", queryArray);
        }


    }
}
